<template>
	<view class="content">
		<view class="floor-room-container">
			<!-- 左侧楼层列表 -->
			<scroll-view class="floor-list" scroll-y>
				<u-sticky>
					<template v-slot:default>
						<view class="floor-title">楼层</view>
						<view 
							class="floor-item" 
							v-for="(item, index) in floorList" 
							:key="item._id"
							:class="{ active: activeFloorIndex === index }"
							@click="changeFloor(index, item._id)"
							@longpress="handleFloorLongPress(item)"
						>
							<text>{{ item.floor_number }}层</text>
						</view>
					</template>
				</u-sticky>
			</scroll-view>
			
			<!-- 右侧房间列表 -->
			<scroll-view class="room-list" scroll-y refresher-enabled 
				:refresher-triggered="isRefreshing"
				@refresherrefresh="onRefresh"
				@refresherrestore="onRestoreRefresh">
				<view v-if="roomList.length === 0" class="no-room">
					<u-empty text="暂无房间" mode="list"></u-empty>
				</view>
				<view v-else class="room-grid">
					<view 
						class="room-item" 
						v-for="item in roomList" 
						:key="item._id"
						:class="{ occupied: item.status === 1 }"
						@click="viewRoomDetail(item)"
						@longpress="handleLongPress(item)"
					>
						<view class="room-image">
							<image 
								:src="item.images && item.images.length > 0 ? item.images[0] : '/static/default-room.png'" 
								mode="aspectFill"
							></image>
							<view v-if="item.status === 1" class="status-tag">已租出</view>
						</view>
						<view class="room-info">
							<view class="room-number">{{ item.room_number }}</view>
							<view class="room-price">{{ item.price }}/月</view>
							<view class="room-type">{{ item.room_type }}</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		
		<!-- 长按操作弹窗 -->
		<u-action-sheet
			:show="showActionSheet"
			:actions="actionOptions"
			@close="showActionSheet = false"
			@select="handleActionSelect"
			title="操作"
			:round="10"
			cancelText="取消"
		></u-action-sheet>
	</view>
</template>

<script setup>
	import { ref, onMounted } from 'vue';
	import { isPermission } from '../../utils/common.js';
	
	// 数据
	const floorList = ref([]);
	const roomList = ref([]);
	const activeFloorIndex = ref(0);
	const showActionSheet = ref(false);
	const currentRoom = ref(null);
	const currentFloor = ref(null);
	const actionOptions = ref([]);
	const isRefreshing = ref(false);
	const actionType = ref(''); // 'room' 或 'floor'
	const token = ref(''); // 定义token变量
	
	// 计算属性 检查用户角色
	const isAdmin = isPermission()
	
	// 生命周期
	onMounted(() => {
		getToken(); // 获取token
		getFloorList();
	});
	
	// 获取token
	const getToken = () => {
		token.value = uni.getStorageSync('uni_id_token') || '';
	};
	
	
	// 获取楼层列表
	const getFloorList = async () => {
		uni.showLoading({
			title: '加载中'
		});
		
		try {
			const res = await uniCloud.callFunction({
				name: 'get-floors',
				getAuthInfo: true
			});
			
			if (res.result.code === 0) {
				floorList.value = res.result.data;
				
				if (floorList.value.length > 0) {
					changeFloor(0, floorList.value[0]._id);
				}
			} else {
				uni.showToast({
					title: res.result.message,
					icon: 'none'
				});
			}
		} catch (e) {
			console.error('获取楼层列表失败', e);
			uni.showToast({
				title: '获取楼层列表失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};
	
	// 切换楼层
	const changeFloor = async (index, floorId) => {
		activeFloorIndex.value = index;
		
		uni.showLoading({
			title: '加载中'
		});
		
		try {
			const res = await uniCloud.callFunction({
				name: 'get-rooms',
				data: {
					floor_id: floorId
				},
				getAuthInfo: true
			});
			
			if (res.result.code === 0) {
				roomList.value = res.result.data;
			} else {
				uni.showToast({
					title: res.result.message,
					icon: 'none'
				});
			}
		} catch (e) {
			console.error('获取房间列表失败', e);
			uni.showToast({
				title: '获取房间列表失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};
	
	// 下拉刷新
	const onRefresh = async () => {
		isRefreshing.value = true;
		
		try {
			// 刷新楼层列表
			await getFloorList();
			
			// 如果有当前选中的楼层，刷新房间列表
			if (activeFloorIndex.value >= 0 && floorList.value.length > 0) {
				await changeFloor(activeFloorIndex.value, floorList.value[activeFloorIndex.value]._id);
			}
		} finally {
			isRefreshing.value = false;
		}
	};
	
	// 恢复下拉刷新状态
	const onRestoreRefresh = () => {
		isRefreshing.value = false;
	};
	
	// 查看房间详情
	const viewRoomDetail = (room) => {
		if (room.status === 0) {
			uni.navigateTo({
				url: `/pages/room-detail/room-detail?id=${room._id}`
			});
		} else {
			uni.showToast({
				title: '该房已租出',
				icon: 'none',
				duration: 2000
			});
		}
	};
	
	// 长按楼层
	const handleFloorLongPress = (floor) => {
		if (!isAdmin) return;
		
		currentFloor.value = floor;
		actionType.value = 'floor';
		
		actionOptions.value = [
			{ name: '删除楼层', color: '#ff4d4f' }
		];
		
		showActionSheet.value = true;
	};
	
	// 长按房间
	const handleLongPress = (room) => {
		if (!isAdmin) return;
		
		currentRoom.value = room;
		actionType.value = 'room';
		
		if (room.status === 0) {
			actionOptions.value = [
				{ name: '标记为已租出', color: '#2867CE' },
				{ name: '编辑房间', color: '#333333' },
				{ name: '删除房间', color: '#ff4d4f' }
			];
		} else {
			actionOptions.value = [
				{ name: '标记为空房', color: '#19be6b' },
				{ name: '编辑房间', color: '#333333' },
				{ name: '删除房间', color: '#ff4d4f' }
			];
		}
		
		showActionSheet.value = true;
	};
	
	// 删除楼层
	const deleteFloor = async (floorId) => {
		uni.showModal({
			title: '确认删除',
			content: '删除楼层将同时删除该楼层下的所有房间，是否继续？',
			success: async (res) => {
				if (res.confirm) {
					uni.showLoading({
						title: '删除中'
					});
					
					try {
						// 确保token是最新的
						getToken();
						
						const res = await uniCloud.callFunction({
							name: 'delete-floor',
							data: {
								floor_id: floorId,
								token: token.value
							}
						});
						
						if (res.result.code === 0) {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							
							// 重新加载楼层列表
							await getFloorList();
						} else {
							uni.showToast({
								title: res.result.message,
								icon: 'none'
							});
						}
					} catch (e) {
						console.error('删除楼层失败', e);
						uni.showToast({
							title: '删除楼层失败',
							icon: 'none'
						});
					} finally {
						uni.hideLoading();
					}
				}
			}
		});
	};
	
	// 删除房间
	const deleteRoom = async (roomId) => {
		uni.showModal({
			title: '确认删除',
			content: '确定要删除这个房间吗？',
			success: async (res) => {
				if (res.confirm) {
					uni.showLoading({
						title: '删除中'
					});
					
					try {
						// 确保token是最新的
						getToken();
						
						const res = await uniCloud.callFunction({
							name: 'delete-room',
							data: {
								room_id: roomId,
								token: token.value
							}
						});
						
						if (res.result.code === 0) {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							
							// 刷新当前楼层的房间列表
							if (activeFloorIndex.value >= 0 && floorList.value.length > 0) {
								await changeFloor(activeFloorIndex.value, floorList.value[activeFloorIndex.value]._id);
							}
						} else {
							uni.showToast({
								title: res.result.message,
								icon: 'none'
							});
						}
					} catch (e) {
						console.error('删除房间失败', e);
						uni.showToast({
							title: '删除房间失败',
							icon: 'none'
						});
					} finally {
						uni.hideLoading();
					}
				}
			}
		});
	};
	
	// 更新房间状态
	const updateRoomStatus = async (roomId, newStatus) => {
		uni.showLoading({
			title: '更新中'
		});
		
		try {
			// 确保token是最新的
			getToken();
			
			const res = await uniCloud.callFunction({
				name: 'update-room-status',
				data: {
					room_id: roomId,
					status: newStatus,
					token: token.value
				}
			});
			
			if (res.result.code === 0) {
				uni.showToast({
					title: '状态更新成功',
					icon: 'success'
				});
				
				// 刷新当前楼层的房间列表
				if (activeFloorIndex.value >= 0 && floorList.value.length > 0) {
					await changeFloor(activeFloorIndex.value, floorList.value[activeFloorIndex.value]._id);
				}
			} else {
				uni.showToast({
					title: res.result.message,
					icon: 'none'
				});
			}
		} catch (e) {
			console.error('更新房间状态失败', e);
			uni.showToast({
				title: '更新房间状态失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};
	
	// 选择操作
	const handleActionSelect = async (e) => {
		const actionName = e.name;
		showActionSheet.value = false;
		
		if (actionType.value === 'room') {
			if (actionName === '编辑房间') {
				uni.navigateTo({
					url: `/pages/edit-room/edit-room?id=${currentRoom.value._id}`
				});
			} else if (actionName === '删除房间') {
				await deleteRoom(currentRoom.value._id);
			} else {
				// 更新房间状态
				const newStatus = actionName === '标记为已租出' ? 1 : 0;
				
				await updateRoomStatus(currentRoom.value._id, newStatus);
			}
		} else if (actionType.value === 'floor') {
			if (actionName === '删除楼层') {
				await deleteFloor(currentFloor.value._id);
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import '@/uni.scss';
	
	.content {
		height: 100vh;
		background-color: #f8f9fa;
	}
	
	.floor-room-container {
		display: flex;
		height: 100%;
		
		.floor-list {
			width: 110px;
			height: 100%;
			background: linear-gradient(to bottom, #ffffff, #f8f9fa);
			box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
			
			.floor-title {
				padding: $spacing-lg;
				font-size: 16px;
				color: #2c3e50;
				font-weight: 600;
				text-align: center;
				border-bottom: 2px solid #edf2f7;
				background: #ffffff;
			}
			
			.floor-item {
				padding: $spacing-lg $spacing-md;
				text-align: center;
				font-size: 15px;
				color: #64748b;
				margin: 4px 8px;
				border-radius: 8px;
				transition: all 0.3s ease;
				
				&.active {
					color: #2563eb;
					background-color: #eff6ff;
					font-weight: 600;
					box-shadow: 0 2px 4px rgba(37, 99, 235, 0.1);
				}
				
				&:active {
					transform: scale(0.98);
					background-color: #e0e7ff;
				}
			}
		}
		
		.room-list {
			flex: 1;
			height: 100%;
			padding: $spacing-lg;
			
			.no-room {
				padding: $spacing-xl 0;
			}
			
			.room-grid {
				display: grid;
				grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
				gap: 12px;
				padding: 8px 0 $spacing-lg;
				
				.room-item {
					background: #ffffff;
					border-radius: 8px;
					box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
					overflow: hidden;
					transition: all 0.3s ease;
					border: 1px solid #edf2f7;
					
					&:hover {
						transform: translateY(-2px);
						box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
					}
					
					&:active {
						transform: scale(0.98);
					}
					
					&.occupied {
						position: relative;
						
						&::after {
							content: '';
							position: absolute;
							top: 0;
							left: 0;
							width: 100%;
							height: 100%;
							background: rgba(0, 0, 0, 0.6);
							z-index: 1;
							pointer-events: none;
						}
						
						.room-image {
							position: relative;
							
							image {
								filter: grayscale(0.3);
							}
							
							.status-tag {
								position: absolute;
								top: 50%;
								left: 50%;
								transform: translate(-50%, -50%);
								background: rgba(37, 99, 235, 0.95);
								color: #ffffff;
								padding: 6px 16px;
								border-radius: 20px;
								font-size: 15px;
								font-weight: 600;
								backdrop-filter: blur(4px);
								box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
								z-index: 2;
								white-space: nowrap;
							}
						}
						
						.room-info {
							position: relative;
							z-index: 2;
							background: rgba(255, 255, 255, 0.9);
							
							.room-number {
								color: #1e293b;
							}
							
							.room-price {
								color: #2563eb;
							}
							
							.room-type {
								background: rgba(248, 250, 252, 0.8);
								color: #1e293b;
							}
						}
					}
					
					.room-image {
						position: relative;
						width: 100%;
						height: 120px;
						overflow: hidden;
						
						image {
							width: 100%;
							height: 100%;
							object-fit: cover;
							transition: transform 0.3s ease;
						}
						
						&:hover image {
							transform: scale(1.05);
						}
					}
					
					.room-info {
						padding: 10px;
						
						.room-number {
							font-size: 15px;
							color: #1e293b;
							font-weight: 600;
							margin-bottom: 4px;
						}
						
						.room-price {
							font-size: 14px;
							color: #2563eb;
							font-weight: 600;
							margin-bottom: 4px;
							display: flex;
							align-items: center;
							
							&::before {
								content: '￥';
								font-size: 12px;
								margin-right: 2px;
								opacity: 0.8;
							}
						}
						
						.room-type {
							font-size: 12px;
							color: #64748b;
							background: #f8fafc;
							padding: 2px 6px;
							border-radius: 4px;
							display: inline-block;
						}
					}
				}
			}
		}
	}
	
	// 添加滚动条样式
	::-webkit-scrollbar {
		width: 6px;
		height: 6px;
	}
	
	::-webkit-scrollbar-track {
		background: #f1f5f9;
		border-radius: 3px;
	}
	
	::-webkit-scrollbar-thumb {
		background: #cbd5e1;
		border-radius: 3px;
		
		&:hover {
			background: #94a3b8;
		}
	}
</style>

